<template>
  <div class="cart-page">
    <HeaderNav />
    
    <div class="main-container" v-loading="loading">
      <!-- 面包屑导航 -->
      <div class="breadcrumb">
        <span class="breadcrumb-item" @click="$router.push('/home')">首页</span>
        <span class="breadcrumb-separator">/</span>
        <span class="breadcrumb-item active">购物车</span>
      </div>

      <!-- 购物车内容 -->
      <div class="cart-container" v-if="cartList.length > 0">
        <!-- 商品列表 -->
        <div class="cart-items">
          <div class="cart-header">
            <div class="select-all">
              <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
            </div>
            <div class="cart-title">购物车商品</div>
          </div>

          <div class="cart-list">
            <div v-for="item in cartList" :key="item.id" class="cart-item">
              <div class="item-checkbox">
                <el-checkbox
                  :model-value="item.selected === 1"
                  @change="(val) => handleSelectItem(item.productId, val)"
                />
              </div>
              <div class="item-image">
                <img 
                  :src="getImageUrl(item.product?.mainImage)" 
                  :alt="item.product?.productName"
                  @error="handleImageError"
                />
              </div>
              <div class="item-info">
                <div class="item-name">{{ item.product?.productName }}</div>
                <div class="item-spec" v-if="item.product">规格：标准</div>
                <div class="item-price">¥ {{ formatPrice(item.product?.price) }}</div>
              </div>
              <div class="item-actions">
                <div class="quantity-control">
                  <button 
                    class="quantity-btn decrease" 
                    @click="handleDecrease(item.productId, item.quantity)"
                    :disabled="item.quantity <= 1"
                  >-</button>
                  <input 
                    type="text" 
                    class="quantity-input" 
                    :value="item.quantity"
                    @change="(e) => handleQuantityInput(item.productId, e.target.value, item.quantity)"
                  />
                  <button 
                    class="quantity-btn increase" 
                    @click="handleIncrease(item.productId, item.quantity)"
                    :disabled="item.quantity >= (item.product?.stockQuantity || 999)"
                  >+</button>
                </div>
                <div class="item-total">¥ {{ formatPrice((item.product?.price || 0) * item.quantity) }}</div>
                <div class="item-delete" @click="handleRemove(item.productId)">删除</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 结算区域 -->
        <div class="cart-summary">
          <div class="summary-title">订单结算</div>

          <div class="summary-row">
            <span class="summary-label">商品金额</span>
            <span class="summary-value">¥ {{ formatPrice(totalAmount) }}</span>
          </div>

          <div class="summary-row">
            <span class="summary-label">运费</span>
            <span class="summary-value">¥ 0.00</span>
          </div>

          <div class="summary-row">
            <span class="summary-label">优惠</span>
            <span class="summary-value">- ¥ 0.00</span>
          </div>

          <div class="summary-total">
            <span>合计：</span>
            <span class="total-amount">¥ {{ formatPrice(totalAmount) }}</span>
          </div>

          <button 
            class="checkout-btn" 
            :disabled="selectedCount === 0"
            @click="handleCheckout"
          >
            立即结算
          </button>

          <div class="balance-info" v-if="userStore.userInfo">
            <span class="balance-label">账户余额：</span>
            <span class="balance-amount">¥ {{ formatPrice(userStore.userInfo.accountBalance) }}</span>
          </div>
        </div>
      </div>

      <!-- 空购物车 -->
      <div class="empty-cart" v-else>
        <div class="empty-icon">🛒</div>
        <div class="empty-text">购物车是空的，快去选购商品吧！</div>
        <el-button type="primary" @click="$router.push('/home')">去购物</el-button>
      </div>

      <!-- 推荐商品 -->
      <div class="recommend-section" v-if="recommendProducts.length > 0">
        <h3 class="section-title">猜你喜欢</h3>

        <div class="product-grid">
          <div 
            v-for="product in recommendProducts" 
            :key="product.id" 
            class="product-card"
            @click="$router.push(`/products/${product.id}`)"
          >
            <div class="product-image">
              <img 
                :src="getImageUrl(product.mainImage)" 
                :alt="product.productName"
                @error="handleImageError"
              />
            </div>
            <div class="product-info">
              <div class="product-name">{{ product.productName }}</div>
              <div class="product-price">¥ {{ formatPrice(product.price) }}</div>
              <div class="product-actions">
                <button 
                  class="add-to-cart" 
                  @click.stop="handleAddToCart(product.id)"
                >
                  加入购物车
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import HeaderNav from '@/components/HeaderNav.vue'
import { useUserStore } from '@/stores/user'
import {
  getCartList,
  updateCartItemQuantity,
  removeFromCart,
  updateSelectedStatus,
  updateAllSelectedStatus,
  calculateTotal,
  addToCart
} from '@/api/cart'
import { getFeaturedProducts } from '@/api/product'
import { getImageUrl, handleImageError as handleImgError } from '@/utils/image'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const cartList = ref([])
const selectAll = ref(false)
const totalAmount = ref(0)
const recommendProducts = ref([])

// 选中商品数量
const selectedCount = computed(() => {
  return cartList.value.filter(item => item.selected === 1).length
})

// 监听购物车列表变化，更新全选状态
watch(cartList, (newList) => {
  selectAll.value = newList.length > 0 && newList.every(item => item.selected === 1)
}, { deep: true })

// 加载购物车列表
const loadCartList = async () => {
  loading.value = true
  try {
    const res = await getCartList()
    if (res.code === 200) {
      cartList.value = res.data || []
      // 更新全选状态
      selectAll.value = cartList.value.length > 0 && cartList.value.every(item => item.selected === 1)
      // 计算总金额
      await loadTotalAmount()
    }
  } catch (error) {
    ElMessage.error('加载购物车失败')
  } finally {
    loading.value = false
  }
}

// 加载总金额
const loadTotalAmount = async () => {
  try {
    const res = await calculateTotal()
    if (res.code === 200) {
      totalAmount.value = res.data || 0
    }
  } catch (error) {
    // 如果接口失败，前端计算
    totalAmount.value = cartList.value
      .filter(item => item.selected === 1)
      .reduce((sum, item) => {
        const price = item.product?.price || 0
        return sum + price * item.quantity
      }, 0)
  }
}

// 加载推荐商品
const loadRecommendProducts = async () => {
  try {
    const res = await getFeaturedProducts({ limit: 4 })
    if (res.code === 200) {
      recommendProducts.value = res.data || []
    }
  } catch (error) {
    console.error('加载推荐商品失败:', error)
  }
}

// 处理全选
const handleSelectAll = async (val) => {
  try {
    await updateAllSelectedStatus(val)
    await loadCartList()
  } catch (error) {
    ElMessage.error('更新选中状态失败')
  }
}

// 处理单个商品选中
const handleSelectItem = async (productId, selected) => {
  try {
    await updateSelectedStatus(productId, selected)
    await loadCartList()
  } catch (error) {
    ElMessage.error('更新选中状态失败')
  }
}

// 处理数量减少
const handleDecrease = async (productId, currentQuantity) => {
  if (currentQuantity <= 1) return
  await handleQuantityChange(productId, currentQuantity - 1)
}

// 处理数量增加
const handleIncrease = async (productId, currentQuantity) => {
  const item = cartList.value.find(item => item.productId === productId)
  const maxQuantity = item?.product?.stockQuantity || 999
  if (currentQuantity >= maxQuantity) {
    ElMessage.warning('库存不足')
    return
  }
  await handleQuantityChange(productId, currentQuantity + 1)
}

// 处理数量输入
const handleQuantityInput = async (productId, value, oldValue) => {
  const quantity = parseInt(value)
  if (isNaN(quantity) || quantity < 1) {
    ElMessage.warning('数量必须大于0')
    await loadCartList() // 恢复原值
    return
  }
  const item = cartList.value.find(item => item.productId === productId)
  const maxQuantity = item?.product?.stockQuantity || 999
  if (quantity > maxQuantity) {
    ElMessage.warning('库存不足')
    await loadCartList() // 恢复原值
    return
  }
  await handleQuantityChange(productId, quantity)
}

// 处理数量变更
const handleQuantityChange = async (productId, quantity) => {
  try {
    await updateCartItemQuantity(productId, quantity)
    await loadCartList()
  } catch (error) {
    ElMessage.error('更新数量失败')
    await loadCartList() // 重新加载恢复原值
  }
}

// 处理删除
const handleRemove = async (productId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
      type: 'warning'
    })
    await removeFromCart(productId)
    ElMessage.success('删除成功')
    await loadCartList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 处理结算
const handleCheckout = () => {
  if (selectedCount.value === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }
  router.push('/order/checkout')
}

// 处理加入购物车
const handleAddToCart = async (productId) => {
  try {
    await addToCart(productId, 1)
    ElMessage.success('已添加到购物车')
    await loadCartList()
  } catch (error) {
    ElMessage.error('添加失败')
  }
}

// 格式化价格
const formatPrice = (price) => {
  if (!price && price !== 0) return '0.00'
  return Number(price).toFixed(2)
}

// 使用统一的图片错误处理
const handleImageError = handleImgError

onMounted(() => {
  loadCartList()
  loadRecommendProducts()
  // 刷新用户信息以获取最新余额
  if (userStore.token) {
    userStore.refreshUserInfo()
  }
})
</script>

<style scoped lang="scss">
.cart-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.main-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

/* 面包屑导航 */
.breadcrumb {
  background-color: white;
  border-radius: 12px;
  padding: 15px 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
}

.breadcrumb-item {
  color: #606266;
  font-size: 14px;
  cursor: pointer;
  
  &.active {
    color: #409EFF;
  }
  
  &:hover:not(.active) {
    color: #409EFF;
  }
}

.breadcrumb-separator {
  margin: 0 8px;
  color: #c0c4cc;
}

/* 购物车内容 */
.cart-container {
  display: flex;
  gap: 20px;
}

/* 商品列表 */
.cart-items {
  flex: 1;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.cart-header {
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
}

.select-all {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.cart-title {
  font-weight: 600;
}

.cart-list {
  max-height: 500px;
  overflow-y: auto;
}

.cart-item {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  
  &:last-child {
    border-bottom: none;
  }
}

.item-checkbox {
  margin-right: 15px;
}

.item-image {
  width: 80px;
  height: 80px;
  background-color: #f5f7fa;
  border-radius: 8px;
  margin-right: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.item-info {
  flex: 1;
}

.item-name {
  font-weight: 500;
  margin-bottom: 5px;
  color: #333;
}

.item-spec {
  color: #909399;
  font-size: 13px;
  margin-bottom: 8px;
}

.item-price {
  color: #f56c6c;
  font-weight: 600;
}

.item-actions {
  display: flex;
  align-items: center;
}

.quantity-control {
  display: flex;
  align-items: center;
  margin-right: 20px;
}

.quantity-btn {
  width: 28px;
  height: 28px;
  background-color: #f5f7fa;
  border: none;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover:not(:disabled) {
    background-color: #e4e7ed;
  }
  
  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
}

.quantity-input {
  width: 50px;
  height: 28px;
  text-align: center;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin: 0 8px;
  
  &:focus {
    outline: none;
    border-color: #409EFF;
  }
}

.item-total {
  font-weight: 600;
  color: #f56c6c;
  margin-right: 20px;
  min-width: 80px;
  text-align: right;
}

.item-delete {
  color: #909399;
  cursor: pointer;
  transition: color 0.3s;
  
  &:hover {
    color: #f56c6c;
  }
}

/* 结算区域 */
.cart-summary {
  width: 300px;
  background-color: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  align-self: flex-start;
}

.summary-title {
  font-weight: 600;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.summary-label {
  color: #606266;
}

.summary-value {
  font-weight: 500;
}

.summary-total {
  display: flex;
  justify-content: space-between;
  margin: 20px 0;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
  font-size: 18px;
  font-weight: 600;
}

.total-amount {
  color: #f56c6c;
}

.checkout-btn {
  width: 100%;
  height: 44px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
  
  &:hover:not(:disabled) {
    background-color: #66b1ff;
  }
  
  &:disabled {
    background-color: #c0c4cc;
    cursor: not-allowed;
  }
}

.balance-info {
  margin-top: 15px;
  padding: 10px;
  background-color: #f0f9ff;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.balance-label {
  color: #606266;
}

.balance-amount {
  color: #409EFF;
  font-weight: 500;
}

/* 空购物车 */
.empty-cart {
  text-align: center;
  padding: 60px 20px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.empty-icon {
  font-size: 60px;
  color: #c0c4cc;
  margin-bottom: 20px;
}

.empty-text {
  color: #909399;
  margin-bottom: 25px;
  font-size: 16px;
}

/* 推荐商品 */
.recommend-section {
  margin-top: 30px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 20px;
  color: #333;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.product-card {
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  cursor: pointer;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  }
}

.product-image {
  height: 150px;
  background-color: #f5f7fa;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.product-info {
  padding: 15px;
}

.product-name {
  font-weight: 500;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #333;
}

.product-price {
  color: #f56c6c;
  font-weight: 600;
  margin-bottom: 12px;
}

.product-actions {
  display: flex;
  justify-content: space-between;
}

.add-to-cart {
  background-color: #409EFF;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: background-color 0.3s;
  
  &:hover {
    background-color: #66b1ff;
  }
}

/* 自定义滚动条 */
.cart-list::-webkit-scrollbar {
  width: 6px;
}

.cart-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.cart-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
  
  &:hover {
    background: #a8a8a8;
  }
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .product-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}

@media (max-width: 768px) {
  .cart-container {
    flex-direction: column;
  }

  .cart-summary {
    width: 100%;
  }

  .product-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .cart-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .item-actions {
    width: 100%;
    justify-content: space-between;
    margin-top: 15px;
  }

  .product-grid {
    grid-template-columns: 1fr;
  }
}
</style>
